from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.contrib import messages
from .forms import UserLoginForm, UserRegisterForm
from django.contrib.auth import logout  # 添加这行导入
from django.shortcuts import redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required  # 添加这行导入


# 添加退出登录视图
def user_logout(request):
    logout(request)
    messages.success(request, '已成功退出登录')
    return redirect('login')

# 添加装饰器保护个人中心页面
@login_required
def user_profile(request):
    return render(request, 'users/profile.html')

# 添加注册视图
def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            messages.success(request, '注册成功！请登录')
            return redirect('login')
        else:
            messages.error(request, '注册失败，请检查输入信息')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})

# 登录视图
def user_login(request):
    if request.method == 'POST':
        form = UserLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                messages.success(request, '登录成功！')
                return redirect('user_profile')
            else:
                messages.error(request, '用户名或密码错误')
    else:
        form = UserLoginForm()
    return render(request, 'users/login.html', {'form': form})

# 个人中心视图
def user_profile(request):
    return render(request, 'users/profile.html')